package fr.iut2.sil1.trolledit.server;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFileImpl extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 8305367618713715640L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");

		FileItem uploadItem = getFileItem(request);
		if (uploadItem == null) {
			response.getWriter().write("NO-SCRIPT-DATA " + uploadItem);
			return;
		}

		try {
			File saveTo = new File(this.getServletContext().getRealPath(uploadItem.getName()));
			System.out.println(saveTo);
			response.getWriter().write("Fichier recupere avec succes !");
			uploadItem.write(saveTo);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private FileItem getFileItem(HttpServletRequest request) {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		System.out.println("passe ");
		try {
			if(isMultipart){
				System.out.println("passe2");
				@SuppressWarnings("rawtypes")
				List items = upload.parseRequest(request);
				System.out.println(upload.toString());
				System.out.println("request: "+request.toString());
				System.out.println("items: "+items.toString());
				
				@SuppressWarnings("rawtypes")
				Iterator it = items.iterator();
				
				System.out.println("it: "+it.toString());
				
				while (it.hasNext()) {
					
					System.out.println("passe3");
					
					FileItem item = (FileItem) it.next();
					if (!item.isFormField() && "uploadFormElement".equals(item.getFieldName())) {
						
						System.out.println("passe4");
						return item;
					}
				}
			}else{
				return null;
			}
		} catch (FileUploadException e) {
			System.out.println(e);
			return null;
		}
		return null;
	}
}
